package com.devyk.av.rtmp.library.camera

import com.devyk.av.camera_recorder.callback.IGLThreadConfig
import com.devyk.av.rtmp.library.utils.LogHelper
import com.devyk.av.rtmp.library.widget.GLSurfaceView
import java.lang.ref.WeakReference

/**
 * <pre>
 *     author  : devyk on 2020-07-08 21:03
 *     blog    : https://juejin.im/user/578259398ac2470061f3a3fb/posts
 *     github  : https://github.com/yangkun19921001
 *     mailbox : yang1001yk@gmail.com
 *     desc    : This is GLThread 自定义 GLThread 线程类，主要用于 OpenGL 的渲染绘制操作
 * </pre>
 */
public open class GLThread(weakReference: WeakReference<IGLThreadConfig>) : Thread() {

    private var TAG = this.javaClass.simpleName

    /**
     * 避免内存泄漏
     */
    private var mWeakIGLThreadConfig: WeakReference<IGLThreadConfig> = weakReference

    /**
     * EGL 环境搭建帮助类
     */
    protected lateinit var mEGLHelper: EglHelper

    /**
     * 对象锁
     */
    private val mLock = Object()

    /**
     * 是否退出线程
     */
    private var isExit = false;

    /**
     * 是否创建线程
     */
    internal var isCreate = false

    /**
     * 窗口是否改变
     */
    internal var isChange = false

    /**
     * 是否开始渲染
     */
    private var isStart = false

    /**
     * 是否停止
     */
    private var isPause = false

    /**
     * 刷新帧率
     */
    private var mDrawFpsRate = 60L

    /**
     * 渲染的 size
     */
    private var mWidth = 1080
    private var mHeight = 1920;


    override fun run() {
        super.run()
        // 实例化 EGL 环境搭建的帮组类
        mEGLHelper = EglHelper()
        // 初始化 EGL
        mWeakIGLThreadConfig.get()?.let { iglThreadConfig ->
            mEGLHelper.initEgl(iglThreadConfig.getSurface(), iglThreadConfig.getEGLContext())
            while (!isExit) {
                when {
                    isPause -> handlePauseState()
                    isStart -> {
                        handleRendererMode(iglThreadConfig)
                        // 开始创建
                        onCreate(mWidth, mHeight)
                        // 改变窗口
                        onChange(mWidth, mHeight)
                        // 开始绘制
                        onDraw()
                    }

                    else -> {
                        this.isStart = true
                    }
                }
            }

            // 结束，释放
            release()
        }
    }

    private fun handlePauseState() {
        try {
            sleep(500)
        } catch (error: InterruptedException) {
            LogHelper.e(TAG, error.message)
        }
    }

    private fun handleRendererMode(iglThreadConfig: IGLThreadConfig) {
        when (iglThreadConfig.getRendererMode()) {
            GLSurfaceView.RENDERER_MODE_WHEN_DIRTY -> {
                synchronized(mLock) {
                    try {
                        mLock.wait()
                    } catch (error: InterruptedException) {
                        LogHelper.e(TAG, error.message)
                    }
                }
            }

            GLSurfaceView.RENDERER_MODE_CONTINUOUSLY -> {
                try {
                    sleep(1000 / mDrawFpsRate)
                } catch (error: InterruptedException) {
                    LogHelper.e(TAG, error.message)
                }
            }

            else -> throw RuntimeException("mRendererMode is wrong value")
        }
    }

    /**
     * 渲染窗口的大小
     */

    fun setRendererSize(width: Int, height: Int) {
        this.mWidth = width
        this.mHeight = height
    }

    /**
     * 渲染器可以创建了
     */
    private fun onCreate(width: Int, height: Int) {
        if (!isCreate) return
        mWeakIGLThreadConfig.get()?.let { view ->
            this.isCreate = false
            view.getRenderer()?.onSurfaceCreate(width, height)
        }
    }

    /**
     * 渲染器需要改变窗口大小
     */
    private fun onChange(width: Int, height: Int) {
        if (!isChange) return
        mWeakIGLThreadConfig.get()?.let { view ->
            this.isChange = false
            view.getRenderer()?.onSurfaceChange(width, height)
        }
    }


    /**
     * 停止渲染
     */

    fun setPause() {
        isPause = true
    }

    /**
     * 恢复渲染
     */

    fun setResume() {
        isPause = false
    }


    /**
     * 渲染器可以开始绘制了
     */
    private fun onDraw() {
        mWeakIGLThreadConfig.get()?.let { view ->
            view.getRenderer()?.onDraw()
            if (!isStart)
                view.getRenderer()?.onDraw()

            // 上面绘制完毕，将绘制完毕的surface提交到屏幕上
            this.mEGLHelper.swapBuffers()
        }
    }

    /**
     * 手动请求刷新
     */
    fun requestRenderer() {
        synchronized(mLock) {
            try {
                mLock.notifyAll()
            } catch (error: Exception) {
                LogHelper.e(TAG, error.message)
            }
        }
    }


    /**
     * 销毁的时候调用
     */
    fun onDestroy() {
        this.isExit = true
        // 避免线程睡眠这里重新刷新一次
        requestRenderer()
    }


    /**
     * 释放资源
     */
    private fun release() {
        mEGLHelper.let { eglHelper ->
            eglHelper.destroyEgl()
        }
        mWeakIGLThreadConfig.clear()
    }

}